var waterPollutionController = WaterPollutionController();
var gasPollutionController = GasPollutionController();
var monitorTable = '#monitorTable';
var monitorTableGas = '#monitorTableGas';
var pageNumber = null;





function MonitorService() {
    var service = {};
    //数据的加载
    service.load = function (monitorPointId) {
        var para = service.getParameter();
        waterPollutionController.getPollutionIntervalRecords(monitorPointId,1,para.pageSize,para.startTime,para.endTime,para.alarmFlag,para.dataType,function (resp) {
            var data = resp.data;
            service.loadTableData(data);
            var total = resp.extra;
            if(total === 0 ){
                total = 1;
            }
            $("#pageTool").jqPaginator({
                totalPages: Math.ceil(total/para.pageSize),
                visiblePages: 1,
                currentPage: 1,
                prev: '<li><a href="javascript:void(0);" style="background-color: #060f1f"><img src="../../common/images/left.png" style="position: relative;top: 6px;"><\/a><\/li>',
                next: '<li><a href="javascript:void(0);" style="background-color: #060f1f"><img src="../../common/images/right.png" style="position: relative;top: 6px;"><\/a><\/li>',
                page: '<li><a href="javascript:void(0);" style="margin-left:5px;margin-right:5px;background-color: #060f1f"> {{page}} / {{totalPages}} <\/a><\/li>',
                onPageChange: function (pageNo) {
                    pageNumber = pageNo;
                    $(monitorTable+" tr:not(:first)").empty("");
                    var p = service.getParameter();
                    waterPollutionController.getPollutionIntervalRecords(monitorPointId,pageNo,p.pageSize,p.startTime,p.endTime,p.alarmFlag,p.dataType,function (resp) {
                        if(resp.result){
                            service.loadTableData(resp.data);
                        }
                        else{
                            layer.alert(resp.description);
                        }
                    });
                }
            });
        });
    };
    //数据表格的加载
    service.loadTableData = function(tableData){
        tableData.map(function (item,index) {
            //增加颜色的判断，加入td单元格的背景颜色
            var recordDataType = service.getParameter().dataType;
            var $trTemp = $("<tr></tr>");
            $trTemp.append("<td style='width: 20%'>"+ common.dateFormatter_hyphen(item.collectTime) +"</td>");
            //dataItemName(nickel,chromium,ph,sewage ),recordDataType,recordId,,
            $trTemp.append("<td style='width: 20%' onclick=openPopup("+"'sewage'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.sewageAvg +"</td>");
            //0正常 1超标 2异常
            //chromiumAvgAlarmFlag phAvgAlarmFlag nickelAvgAlarmFlag
            switch (item.phAvgAlarmFlag ) {
                case 0:
                    $trTemp.append("<td style='width: 20%;' onclick=openPopup("+"'ph'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.phAvg +"</td>");
                    break;
                case 1:
                    $trTemp.append("<td style='width: 20%;background-color: #f5a623;color: #0C0C0C' onclick=openPopup("+"'ph'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.phAvg +"</td>");
                    break;
                case 2:
                    $trTemp.append("<td style='width: 20%;background-color: #d0021b;color: #0C0C0C' onclick=openPopup("+"'ph'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.phAvg +"</td>");
                    break;
            }

            switch (item.chromiumAvgAlarmFlag ) {
                case 0:
                    $trTemp.append("<td style='width: 20%;' onclick=openPopup("+"'chromium'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.chromiumAvg +"</td>");
                    break;
                case 1:
                    $trTemp.append("<td style='width: 20%;background-color: #f5a623;color: #0C0C0C' onclick=openPopup("+"'chromium'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.chromiumAvg +"</td>");
                    break;
                case 2:
                    $trTemp.append("<td style='width: 20%;background-color: #d0021b;color: #0C0C0C' onclick=openPopup("+"'chromium'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.chromiumAvg +"</td>");
                    break;
            }

            switch (item.nickelAvgAlarmFlag ) {
                case 0:
                    $trTemp.append("<td style='width: 20%;' onclick=openPopup("+"'nickel'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.nickelAvg +"</td>");
                    break;
                case 1:
                    $trTemp.append("<td style='width: 20%;background-color: #f5a623;color: #0C0C0C' onclick=openPopup("+"'nickel'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.nickelAvg +"</td>");
                    break;
                case 2:
                    $trTemp.append("<td style='width: 20%;background-color: #d0021b;color: #0C0C0C' onclick=openPopup("+"'nickel'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.nickelAvg +"</td>");
                    break;
            }
            $trTemp.appendTo(monitorTable);
        });
    };

    //获取今天的0点是23:59时间
    service.getTodayTime = function () {
        var start = new Date(new Date(new Date().toLocaleDateString()).getTime());
        var end = new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1);
        return {start:start,end:end};
    };

    //获取load加载所需要的所有参数
    service.getParameter = function () {
        var alarmFlag = $("#alarmFlag").val();

        var startTime = common.dateFormatter_inverse($("#startTime").val());
        var endTime = common.dateFormatter_inverse($("#endTime").val());
        var dataType = $("#dataType").val();
        var pageSize = $("#pageSize").val();
        return {
            alarmFlag:alarmFlag,
            startTime:startTime,
            endTime:endTime,
            dataType:dataType,
            pageSize:pageSize
        }
    };

    //隐藏所有的table
    service.hiddenAllTable = function () {
        $("#info").css('display','none');
        $("#phInfo").css('display','none');
        $("#NiInfo").css('display','none');
        $("#CrInfo").css('display','none');
    };

    //弹窗所需的详细数据项查询
    service.getDataItemDetail = function(dataItemName,recordDataType,recordId){
        waterPollutionController.getDataItemDetail(recordDataType,recordId,dataItemName,function (resp) {
            var data = resp.data;
            monitorService.hiddenAllTable();
            switch(dataItemName)
            {
                case 'sewage':
                    $("#info").css('display','block');
                    service.loadInfoPopup(data);
                    break;
                case 'ph':
                    $("#phInfo").css('display','block');
                    service.loadPhPopup(data);
                    break;
                case 'chromium':
                    $("#CrInfo").css('display','block');
                    service.loadCrPopup(data);
                    break;
                case 'nickel':
                    $("#NiInfo").css('display','block');
                    service.loadNiPopup(data);
                    break;
            }
        })
    };

    //加载info弹窗
    service.loadInfoPopup = function (data) {
        console.log(data);
        $("#infoMonitorPointName").html(data.monitorPointName);
        $("#infoCollectTime").html(common.dateFormatter_hyphen(data.collectTime));
        $("#infoAvg").html(data.avg);
        $("#infoMax").html(data.max);
        $("#infoMin").html(data.min);
        $("#infoAvg").html(data.min);
        $("#infoCou").html(data.cou);
    };

    //加载ph弹窗
    service.loadPhPopup = function (data) {
        console.log(data)
        $("#phMonitorPointName").html(data.monitorPointName);
        $("#phCollectTime").html(common.dateFormatter_hyphen(data.collectTime));
        $("#phAvg").html(data.avg);
        $("#phMax").html(data.max);
        $("#phMin").html(data.min);
        $("#phAvg").html(data.avg);
        var alarm = data.thresholdConfig.alarmLowerLimit+'-'+data.thresholdConfig.alarmUpperLimit;
        var normal = data.thresholdConfig.normalValueLowerLimit+'-'+data.thresholdConfig.normalValueUpperLimit;
        $("#phAlarmLimit").html(alarm);
        $("#phNormalLimit").html(normal);

    };

    //加载ni弹窗
    service.loadNiPopup = function (data) {
        console.log(data);
        $("#niMonitorPointName").html(data.monitorPointName);
        $("#niCollectTime").html(common.dateFormatter_hyphen(data.collectTime));
        $("#niAvg").html(data.avg);
        $("#niMax").html(data.max);
        $("#niMin").html(data.min);
        $("#niCou").html(data.cou);
        var alarm = data.thresholdConfig.alarmLowerLimit+'-'+data.thresholdConfig.alarmUpperLimit;
        var normal = data.thresholdConfig.normalValueLowerLimit+'-'+data.thresholdConfig.normalValueUpperLimit;
        $("#niAlarmLimit").html(alarm);
        $("#niNormalLimit").html(normal);
    };

    //加载cr弹窗
    service.loadCrPopup = function (data) {
        console.log(data);
        $("#crMonitorPointName").html(data.monitorPointName);
        $("#crCollectTime").html(common.dateFormatter_hyphen(data.collectTime));
        $("#crAvg").html(data.avg);
        $("#crMax").html(data.max);
        $("#crMin").html(data.min);
        $("#crCou").html(data.cou);
        var alarm = data.thresholdConfig.alarmLowerLimit+'-'+data.thresholdConfig.alarmUpperLimit;
        var normal = data.thresholdConfig.normalValueLowerLimit+'-'+data.thresholdConfig.normalValueUpperLimit;
        $("#crAlarmLimit").html(alarm);
        $("#crNormalLimit").html(normal);
    };

    return service;
}

var monitorService = MonitorService();

function GasMonitorService() {
    var service = {};
    //数据的加载
    service.load = function (monitorPointId) {
        var para = service.getParameter();
        gasPollutionController.getPollutionRtdRecords(monitorPointId,1,para.pageSize,para.startTime,para.endTime,para.alarmFlag,function (resp) {
            var data = resp.data;
            service.loadTableData(data);
            var total = resp.extra;
            if(total === 0 ){
                total = 1;
            }
            $("#pageTool").jqPaginator({
                totalPages: Math.ceil(total / para.pageSize),
                visiblePages: 1,
                currentPage: 1,
                prev: '<li><a href="javascript:void(0);" style="background-color: #060f1f"><img src="../../common/images/left.png" style="position: relative;top: 6px;"><\/a><\/li>',
                next: '<li><a href="javascript:void(0);" style="background-color: #060f1f"><img src="../../common/images/right.png" style="position: relative;top: 6px;"><\/a><\/li>',
                page: '<li><a href="javascript:void(0);" style="margin-left:5px;margin-right:5px;background-color: #060f1f"> {{page}} / {{totalPages}} <\/a><\/li>',
                onPageChange: function (pageNo) {
                    pageNumber = pageNo;
                    $(monitorTableGas+" tr:not(:first)").empty("");
                    var p = service.getParameter();
                    gasPollutionController.getPollutionRtdRecords(monitorPointId,pageNo,p.pageSize,p.startTime,p.endTime,p.alarmFlag,function (resp) {
                        // service.loadTableData(resp.data);
                        if(resp.result){
                            service.loadTableData(resp.data);
                        }
                        else{
                            layer.alert(resp.description);
                        }
                    });
                }
            });

        });
    };
    //数据表格的加载
    service.loadTableData = function(tableData){
        tableData.map(function (item,index) {
            //增加颜色的判断，加入td单元格的背景颜色
            var recordDataType = service.getParameter().dataType;
            var $trTemp = $("<tr></tr>");
            $trTemp.append("<td style='width: 33.3%'>"+ common.dateFormatter_hyphen(item.collectTime) +"</td>");
            //0正常 1超标 2异常
            //chromiumAvgAlarmFlag phAvgAlarmFlag nickelAvgAlarmFlag
            switch (item.vocAlarmFlag){
                case 0:
                    $trTemp.append("<td style='width: 33.3%;' onclick=openGasPopup("+"'voc'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.voc +"</td>");
                    break;
                case 1:
                    $trTemp.append("<td style='width: 33.3%;background-color: #f5a623;color: #0C0C0C' onclick=openGasPopup("+"'voc'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.voc +"</td>");
                    break;
                case 2:
                    $trTemp.append("<td style='width:33.3%;background-color: #d0021b;color: #0C0C0C' onclick=openGasPopup("+"'voc'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.voc +"</td>");
                    break;
            }

            switch (item.tolueneAlarmFlag) {
                case 0:
                    $trTemp.append("<td style='width: 33.3%;' onclick=openGasPopup("+"'toluene'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.toluene +"</td>");
                    break;
                case 1:
                    $trTemp.append("<td style='width: 33.3%;background-color: #f5a623;color: #0C0C0C' onclick=openGasPopup("+"'toluene'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.toluene +"</td>");
                    break;
                case 2:
                    $trTemp.append("<td style='width: 33.3%;background-color: #d0021b;color: #0C0C0C' onclick=openGasPopup("+"'toluene'"+",'"+recordDataType+"'"+",'"+item.id+"'"+")>"+ item.toluene +"</td>");
                    break;
            }
            $trTemp.appendTo(monitorTableGas);
        });
    };

    //获取今天的0点是23:59时间
    service.getTodayTime = function () {
        var start = new Date(new Date(new Date().toLocaleDateString()).getTime());
        var end = new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1);
        return {start:start,end:end};
    };
    //获取load加载所需要的所有参数
    service.getParameter = function () {
        var alarmFlag = $("#alarmFlag").val();
        var startTime = common.dateFormatter_inverse($("#startTime").val());
        var endTime = common.dateFormatter_inverse($("#endTime").val());
        var dataType = $("#dataType").val();
        var pageSize = $("#pageSize").val();
        return {
            alarmFlag:alarmFlag,
            startTime:startTime,
            endTime:endTime,
            dataType:dataType,
            pageSize:pageSize
        }
    };

    //弹窗所需的详细数据项查询
    service.getDataItemDetail = function(dataItemName,recordDataType,recordId){
        gasPollutionController.getDataItemDetail(recordId,dataItemName,function (resp) {
            var data = resp.data;
            service.hiddenAllTable();
            console.log(dataItemName,data);
            switch(dataItemName)
            {
                case 'voc':
                    $("#VocInfo").css('display','block');
                    service.loadVocPopup(data);
                    break;
                case 'toluene':
                    $("#TolueneInfo").css('display','block');
                    service.loadToluenePopup(data);
                    break;
            }
        })
    };

    //加载info弹窗
    service.loadVocPopup = function (data) {
        $("#vocMonitorPointName").html(data.monitorPointName);
        $("#vocCollectTime").html(common.dateFormatter_hyphen(data.collectTime));
        var alarm = data.thresholdConfig.alarmLowerLimit+'-'+data.thresholdConfig.alarmUpperLimit;
        var normal = data.thresholdConfig.normalValueLowerLimit+'-'+data.thresholdConfig.normalValueUpperLimit;
        $("#vocAlarmLimit").html(alarm);
        $("#vocNormalLimit").html(normal);
        $("#vocRtd").html(data.rtd);
    };

    //加载ph弹窗
    service.loadToluenePopup = function (data) {
        $("#tolueneMonitorPointName").html(data.monitorPointName);
        $("#tolueneCollectTime").html(common.dateFormatter_hyphen(data.collectTime));
        var alarm = data.thresholdConfig.alarmLowerLimit+'-'+data.thresholdConfig.alarmUpperLimit;
        var normal = data.thresholdConfig.normalValueLowerLimit+'-'+data.thresholdConfig.normalValueUpperLimit;
        $("#tolueneAlarmLimit").html(alarm);
        $("#tolueneNormalLimit").html(normal);
        $("#tolueneRtd").html(data.rtd);
    };

    //隐藏所有的table
    service.hiddenAllTable = function () {
        $("#info").css('display','none');
        $("#phInfo").css('display','none');
        $("#NiInfo").css('display','none');
        $("#CrInfo").css('display','none');
        $("#VocInfo").css('display','none');
        $("#TolueneInfo").css('display','none');
    };

    return service;
}

var gasMonitorService = GasMonitorService();

function init() {
    //时间选择器
    laydate.render({
        elem: '#startTime', //指定元素
        theme: '#060f1f',
        type: 'datetime',
        value:monitorService.getTodayTime().start
    });
    laydate.render({
        elem: '#endTime', //指定元素
        theme: '#060f1f',
        type: 'datetime',
        value:monitorService.getTodayTime().end
    });
    //数据加载
    monitorService.load(parent.monitorPointId);
    //分页显示数量的重置
    $("#pageSize").on('change', function () {
        $('#pageTool').jqPaginator('destroy');
        monitorService.load(parent.monitorPointId);
    });

    //搜索功能
    $("#search").on('click', function () {
        $('#pageTool').jqPaginator('destroy');
        monitorService.load(parent.monitorPointId);
    });


}

//打开弹窗
function openPopup(dataItemName,recordDataType,recordId){
    monitorService.getDataItemDetail(dataItemName,recordDataType,recordId);
    $('#code').center();
    $('#goodcover').show();
    $('#code').show();
    parent.$("#leftMenu").addClass('mask');
    parent.$("#rightMenu").addClass('mask');
}

function openGasPopup(dataItemName,recordDataType,recordId){
    //甲苯，没用，id
    gasMonitorService.getDataItemDetail(dataItemName,recordDataType,recordId);

    $('#code').center();
    $('#goodcover').show();
    $('#code').show();
    parent.$("#leftMenu").addClass('mask');
    parent.$("#rightMenu").addClass('mask');
}

function monitorGasInit(){
    //时间选择器
    laydate.render({
        elem: '#startTime', //指定元素
        theme: '#060f1f',
        type: 'datetime',
        value:monitorService.getTodayTime().start
    });
    laydate.render({
        elem: '#endTime', //指定元素
        theme: '#060f1f',
        type: 'datetime',
        value:monitorService.getTodayTime().end
    });

    gasMonitorService.load(parent.monitorPointId);

    //分页显示数量的重置
    $("#pageSize").on('change', function () {
        $('#pageTool').jqPaginator('destroy');
        gasMonitorService.load(parent.monitorPointId);
    });

    //搜索功能
    $("#search").on('click', function () {
        $('#pageTool').jqPaginator('destroy');
        gasMonitorService.load(parent.monitorPointId);
    });

};

$(function () {

    //1是污水，2是大气
    switch (parent.monitorPointId) {
        case '2':
            $(monitorTableGas).css('display','table');
            $(monitorTable).css('display','none');
            $("#dataType").empty();
            $("#dataType").append("<option selected value='Value'>实时数据</option>");
            monitorGasInit();
            break;
        case '1':
            init();
            break;
    }
});

